package com.ruoyi.system.config;

import com.alibaba.fastjson2.JSON;
import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.ruoyi.common.redis.component.RedisTemplateManager;
import com.ruoyi.common.redis.domain.RedisInfo;
import com.ruoyi.common.tenant.component.TenantDataSourceManager;
import com.ruoyi.common.tenant.domain.DataSourceInfo;
import com.ruoyi.common.tenant.domain.SysTenant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.annotation.Resource;

@Configuration
@Slf4j
@Primary
public class CustomTenantConfig extends TenantDataSourceManager {

    @Resource
    private RedisTemplateManager redisTemplateManager;
    /**
     * 刷新 数据源的同时，新增对应redisTemplate
     * @param tenant 变更后的数据信息
     */
    @Override
    public void dynamicDataSource(DynamicRoutingDataSource ds, SysTenant tenant, DataSourceInfo dataSourceInfo) {
        super.dynamicDataSource(ds, tenant, dataSourceInfo);
        RedisInfo redisInfo = JSON.parseObject(tenant.getRedisDataSource(), RedisInfo.class);
        redisTemplateManager.dynamicRedisTemplate(tenant.getTenantId(),redisInfo);
        log.info("refresh redis success! after:[{}]", tenant);
    }
}
